package com.contextor.magiccards.dao;

import com.contextor.magiccards.model.Entity;
import com.contextor.magiccards.model.errors.MagicCardsException;
import com.contextor.magiccards.model.errors.dao.ObjectNotFoundException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * User: sergey
 * Date: Mar 10, 2011 4:10:38 PM
 */
@Service
public abstract class BaseDao<T extends Entity, PK extends Serializable> extends HibernateDaoSupport implements GenericDao<T, PK> {

    protected Class<T> clazz;

    protected BaseDao(Class<T> t) {
        this.clazz = t;
    }

    public T getById(int shardId, PK pk) {
        return (T) this.getHibernateTemplate().get(clazz, pk);
    }

    public T exist(int shardId, PK pk) throws MagicCardsException {
        T t = (T) this.getHibernateTemplate().get(clazz, pk);
        if (t == null)
            throw new ObjectNotFoundException("Can't find " + clazz.getSimpleName() + " by id=" + pk);
        return t;
    }

    public T loadById(int shardId, PK pk) {
        return this.getHibernateTemplate().load(clazz, pk);
    }

    public void save(int shardId, T bean) {
        this.getHibernateTemplate().saveOrUpdate(bean);
    }

    @SuppressWarnings("unchecked")
    public void remove(int shardId, PK pk) throws Exception {
        final Entity obj = clazz.newInstance();
        obj.setId(pk);
        this.getHibernateTemplate().delete(obj);
    }

    @Autowired()
    @Qualifier("sessionFactory")
    public void setFactory(SessionFactory factory) {
        this.setSessionFactory(factory);
    }
}
